package controllers;

import helpers.ValidateHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.EmailData;
import datastore.EmailDataFile;
import datastore.EmailDataStore;
import debugs.EmailDataStoreDebug;

import models.EmailModel;

public class CancelEmailServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/pages/cancel_email.jsp").forward(request, response);
		} catch (ServletException e) {

		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String strEmail = (String) request.getParameter("email");
		
		TreeMap check = new TreeMap();
		
		if (!ValidateHelper.isEmail(strEmail)) {
			check.put("email", "Bạn nhập email không đúng!");
		}
		
		if (check.size() == 0) {
			EmailData emailData = new EmailData();
			EmailModel email = emailData.getEmail(strEmail);
			if (email != null) {
				emailData.delete(email);
				
				//Remove email file
				EmailDataStore emailDataStore = EmailDataFile.getEmailByFileName(email.getCity());
				List<String> emails = new ArrayList<String>();
				if (emailDataStore != null) {
					emails = emailDataStore.getEmails();
					emails.remove(strEmail);
					emailDataStore.setEmails(emails);
					EmailDataFile.savePage(emailDataStore);
					EmailDataStoreDebug.debug(emailDataStore);
				}
			}
			request.setAttribute("success", "Bạn đã hủy nhận mail thành công.");
			
		}
		
		request.setAttribute("check", check);
		request.setAttribute("email", strEmail);
		try {
			request.getRequestDispatcher("/pages/cancel_email.jsp").forward(request, response);
		} catch (ServletException e) {

		}
	}
}
